package com.gmrz.uap.job;

import com.gmrz.uap.cache.AmmsCacheUtil;
import com.gmrz.uap.cfg.SystemConst;
import com.gmrz.uap.datastatistics.DataStatisticsService;
import com.gmrz.uap.model.FidoLog;
import com.gmrz.uap.model.UasConfig;
import com.gmrz.uap.util.DateUtil;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.tx.Tx;
import org.joda.time.DateTime;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.sql.SQLException;

public class DeleteFIdoLogJob implements Job {

    private static boolean lock = false;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            // 根据随机生成的随机毫秒数来进行休眠
            System.out.println("DeleteFIdoLogJob 线程休眠.....");
            Thread.sleep(DataStatisticsService.me.getRandomSleepMinutes());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(!lock) {
            String key = TaskConst.DELETEFIDOLOGJOB_CACHE_KEY;
            key = key + DateUtil.getToday();
            boolean lockFlag = false;
            try {
                lock = true;
                lockFlag = AmmsCacheUtil.getCacheStoreService().tryGetDistributedLock(key,TaskConst.JOB_CACHE_VALUE,TaskConst.AAIDSTATISTICSDAYJOB_CACHE_TiME);
                if(lockFlag) {
                    String retainDay = UasConfig.dao.getValueByKey("uaf.log.retention.days");
                    int days = 0;
                    if (null != retainDay && !"".equals(retainDay.trim())) {
                        days = Integer.parseInt(retainDay);
                    }
                    if (days > 0) {
                        // 计算出保留天数之前的日期时间
                        final DateTime retainDateTime = new DateTime().minusDays(Integer.parseInt(retainDay));

                        //获取保留日期之前的日志记录数
                        //long fidoLogCount = FidoLog.dao.findByGreaterThanDay(retainDateTime.toString("yyyy-MM-dd"));
                        // 获取业务历史日志表中数据的最大时间
                        final String maxCreatesOnFidoLogHis = FidoLog.dao.findMaxCreatesOnFidoLogHis();

                        int deleteCount = 0;
                        long s = System.currentTimeMillis();

                        // 事务支持,需要先指定数据源，否则事务将不生效
                        boolean flag = Db.use(SystemConst.DB_FIDOLOG_DATASOURCE).tx(new IAtom() {
                            @Override
                            public boolean run() throws SQLException {
                                // 将日志表中过期的日志复制到历史表中，同时关闭历史表的日志记录功能；
                                int insertCount = FidoLog.dao.insertHisByGreaterThanDay(retainDateTime.toString("yyyy-MM-dd HH:mm:ss"), maxCreatesOnFidoLogHis);

                                if (insertCount == -1) {
                                    return false;
                                }
                                return true;
                            }
                        });
                        if (!flag) throw new RuntimeException();

                        do {
                            deleteCount = FidoLog.dao.deleteByGreaterThanDay(retainDateTime.toString("yyyy-MM-dd HH:mm:ss"));
                        } while (deleteCount > 0);

                        System.out.println("delete log all time:" + (System.currentTimeMillis() - s));
                    }
                }
            }finally {
                lock = false;
                if(lockFlag){
                    AmmsCacheUtil.getCacheStoreService().releaseDistributedLock(key,TaskConst.JOB_CACHE_VALUE);
                }
            }
        }
    }
}
